package com.jack.payment.config;


import com.jack.payment.cache.CacheRedisServiceImpl;
import com.jack.payment.constant.SettingRuleConstant;
import com.jack.payment.entity.business.PaymentInitBo;
import com.jack.payment.entity.common.BusinessException;
import com.jack.payment.service.basic.impl.ProjectConfigServiceImpl;
import com.jack.payment.service.strategy.PaymentContext;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 项目初始化
 */
@Component
public class ProjectInitConfig {
    private Logger log = LoggerFactory.getLogger(ProjectInitConfig.class);

    @Value("${paymentEnv}")
    private String paymentEnv;

    @Autowired
    private CacheRedisServiceImpl cacheRedisService;
    @Autowired
    private PaymentContext paymentContext;
    @Autowired
    private ProjectConfigServiceImpl projectConfigService;


    /**
     * 指定本支付服务的环境状态, 执行 支付环境配置
     */
    public void initThisProjectPaymentEnv() throws BusinessException {
        // 获取基础的支付环境key
        String fullPaymentEnvStr = SettingRuleConstant.PAYMENT_ENV + paymentEnv;
        PaymentInitBo paymentInitBo = cacheRedisService.getCacheRuleContent(fullPaymentEnvStr);
        Class<?> clazz = paymentInitBo.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                PaymentInitBo.PaymentInitMethodBo methodBo = (PaymentInitBo.PaymentInitMethodBo) field.get(paymentInitBo);
                paymentContext.getInitPaymentConfigData(methodBo);
            } catch (IllegalAccessException e) {
                log.error("反射获取值异常 具体错误如下 "  + e);
            }
        }
    }

    public void initEmailSendConfig() {
        projectConfigService.configProjectSendEmail("2");
    }

    /**
     * 执行项目初始 配置
     * @throws BusinessException
     */
    @PostConstruct
    public void initProjectConfigEnv() throws BusinessException {
        initThisProjectPaymentEnv();
        initEmailSendConfig();
    }
}
